#Python's file reading and writing
File I/O is one of the most basic operations. Python uses the built-in function open
to open files, then the read
method to read files, the write
method to write to files, and finally the close
method to close the files.
f = open('./1.txt', 'w') # 'w' means open file in write-only mode
f.write('Test')
f.close()
f = open('./1.txt', 'r') # 'r' means open file in read-only mode
text = f.read()
print(text)
f.close()
#File Opening Modes
r
: Read mode; throws error if file does not exist.w
: Write mode; clears existing file if it exists.a
: Append mode; offset starts at file end.+
: Read and write mode.b
: Binary mode, typically used for non-text files like images or executables.
Mode | Description | File Exists | File Not Exist | Initial Offset | Return Type |
---|---|---|---|---|---|
r | Read-only | Opens file | Raises FileNotFoundError | File start | str |
w | Write-only | Clears file | Creates new file | File start | str |
a | Append write | Opens file | Creates new file | File end | str |
r+ | Read and write | Opens file | Raises FileNotFoundError | File start | str |
w+ | Read and write | Clears file | Creates new file | File start | str |
a+ | Append read and write | Opens file | Creates new file | File end | str |
rb | Read-only (binary) | Opens file | Raises FileNotFoundError | File start | bytes |
wb | Write-only (binary) | Clears file | Creates new file | File start | bytes |
ab | Append write (binary) | Opens file | Creates new file | File end | bytes |
rb+ | Read/write (binary) | Opens file | Raises FileNotFoundError | File start | bytes |
wb+ | Read/write (binary) | Clears file | Creates new file | File start | bytes |
ab+ | Append read/write(binary) | Opens file | Creates new file | File end | bytes |
#File Offset
The file offset marks the current position for reading or writing in the file. In Python, use the tell()
method to get the offset and seek()
to set the offset. Reading or writing automatically advances the offset.
- For text files, the offset unit is characters.
- For binary files (opened with
b
mode), the offset unit is bytes.
import io
f = open('./1.txt', 'w')
print('Offset when opening file:', f.tell()) # Check offset
f.write('ABCDEFGHIJKLMNOPQRSTUVWXYZ') # Write content
print('Offset after writing:', f.tell()) # Check offset
f.close()
f = open('./1.txt', 'rb')
print('Offset when opening file:', f.tell())
f.seek(10, io.SEEK_SET) # Offset = file start + 10 bytes
print('Current offset:', f.tell())
f.seek(-9, io.SEEK_END) # Offset = file end - 9 bytes
print('Current offset:', f.tell())
f.seek(-5, io.SEEK_CUR) # Offset = current position - 5 bytes
print('Current offset:', f.tell())
Writing in the middle of a file overwrites existing content, it does not insert:
import io
f = open('./1.txt', 'w')
f.write('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
f.seek(10, io.SEEK_SET)
f.write('XXXXXXXX') # Overwrites at offset 10
f.close()
f = open('./1.txt', 'r')
print(f.read())
#Using with
Manually closing files every time can be tedious and if an error occurs, the file might not be closed properly. In Python, with
statement solves this:
with open('/path/to/file', 'r') as f:
pass
When the with
block ends, f.__exit__()
is automatically called to close the file, regardless of normal or exceptional exit.
Any object with
__enter__
and__exit__
methods can be used withwith
. Upon enteringwith
,__enter__
is called automatically; upon leaving,__exit__
is called.
Example:
class Refrigerator:
def __enter__(self):
print('Opening refrigerator')
def __exit__(self, type, value, traceback):
print('Closing refrigerator')
refrigerator = Refrigerator()
with refrigerator:
pass